#!/usr/bin/env php
<?php
// 替换后的下载地址前缀
$baseURL = 'https://file.winegame.net/winetricks';

if (!isset($argv[1])) {
    usage();
}
$path = $argv[1];

if (isset($argv[2])) {
    $baseURL = $argv[2];
}

$lines = file($path);
$winetricks = file_get_contents($path);

$manualDownload = "以下地址中存在变量，需要手动下载，完整的下载地址可通过分析 winetricks 脚本得到：\n\n";

$downloadScript = <<<'EOF'
#!/bin/bash

JOBS=1

if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
    echo "Usage:"
    echo -e "\t$0 [concurrentJobs]"
    echo
    echo "Example:"
    echo -e "\t$0"
    echo -e "\t$0 5"
    exit
fi

if ! [ "$1" = "" ]; then
    JOBS="$1"
fi

aria2c_download() {
    aria2c --allow-overwrite=true -x 5 -s 5 -c -d "$1" -o "$2" "$3" \
        && echo "$3 -> $1/$2" >> ./success.log \
        || echo "$3 -> $1/$2" >> ./failed.log
}

download() {
    if [ "$JOBS" = "0" ]; then
        exit
    fi

    if [ "$JOBS" = "1" ]; then
        echo -e "\n\n------------------------ Files: $1/$FILE_COUNT, Jobs: 1/$JOBS ------------------------\n"
        aria2c_download "$2" "$3" "$4"
        return
    fi

    while true; do
        aria2cNum=$(ps ax | grep aria2c | grep -v grep | wc -l)
        echo -e "\n\n------------------------ Files: $1/$FILE_COUNT, Jobs: $aria2cNum/$JOBS ------------------------\n"
        if [ "$aria2cNum" -ge "$JOBS" ]; then
            sleep 1
        else
            aria2c_download "$2" "$3" "$4" &
            return
        fi
    done
}

trap "JOBS=0; killall aria2c; exit" INT

run() {

EOF;


$fileUrlMap = [];
$fileCount = 0;

foreach ($lines as $line) {
    if (preg_match('/^\s*#/', $line)) {
        continue;
    }
    if (preg_match('@https?://[^\s]*@i', $line, $arr)) {
        $url = trim($arr[0], '"\',');

        // 不在 w_download 函数里通常不是安装包
        if (strpos($line, 'w_download') === FALSE) {
            continue;
        }

        // 存在变量，需要手动下载
        if (strpos($url, '$') !== FALSE) {
            $manualDownload .= "$url\n";
        }

        $file = urldecode(preg_replace('/\?.*$/', '', $url));
        $file = preg_replace('@https?://@i', '', $file);

        if (substr($file, -1) == '/') {
            $file .= 'file';
        }

        if (isset($fileUrlMap[$file])) {
            if ($fileUrlMap[$file] !== $url) {
                echo "文件名冲突，需要手动解决:\n文件: $file\nURL1: {$fileUrlMap[$file]}\nURL2: $url\n";
                exit;
            } else {
                continue;
            }
        }

        $fileUrlMap[$file] = $url;

        $dirParam = escapeshellarg(dirname($file));
        $basenameParam = escapeshellarg(basename($file));
        $urlParam = escapeshellarg($url);

        preg_match('#(\?.*)$#', $url, $queryString);
        $queryString = isset($queryString[1]) ? $queryString[1] : '';
        
        // 使用七牛云附件名称参数
        $queryString = preg_replace('/([?&])(f|filename|product)=/i', '$1attname=', $queryString);
        
        $newURL = escapeURL("$baseURL/$file$queryString");
    
        $fileCount++;
        $downloadScript .= "download $fileCount $dirParam $basenameParam $urlParam\n";
        $winetricks = str_replace($url, $newURL, $winetricks);

        echo "$url -> $newURL\n";
    }
}

$downloadScript .= <<<EOF
}

FILE_COUNT=$fileCount

run

EOF;

// 添加禁止winetricks版本检查的环境变量，防止打不开github的用户卡住。
// 添加禁止box86和box64输出日志的代码，防止在arm64中捕获输出时出错。
$winetricks = str_replace("\nWINETRICKS_VERSION=", <<<EOF


export BOX86_NOBANNER=1
export BOX86_LOG=NONE
export BOX64_NOBANNER=1
export BOX64_LOG=NONE

if [ "\$WINETRICKS_NETWORK_DEBUG" = "enabled" ]; then
    source "\$(dirname "\$0")/network-debug.sh"
fi

WINETRICKS_LATEST_VERSION_CHECK=disabled
WINETRICKS_VERSION=
EOF
, $winetricks);

file_put_contents("$path-manual-download.txt", $manualDownload);
file_put_contents("$path-replaced", $winetricks);
file_put_contents("$path-download.sh", $downloadScript);

chmod("$path-replaced", 0755);
chmod("$path-download.sh", 0755);

function usage() {
    global $argv, $baseURL;
    echo "Usage:\n";
    echo "\t$argv[0] <file> [baseURL]\n";
    echo "\n";
    echo "Example:\n";
    echo "\t$argv[0] ./winetricks\n";
    echo "\t$argv[0] ./winetricks $baseURL\n";
    exit;
}

function escapeURL($url) {
    return str_replace(' ', '%20', $url);
}
